package com.xx566.blog.model;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * 留言
 */
@SuppressWarnings("serial")
public class Message extends Model<Message> {

	public static final Message dao = new Message();

	public List<Message> findAll() {
		return find("select * from message order by createtime desc");
	}

	public Page<Message> findMessages4Page(int pagenum, int pageSize) {
		Page<Message> page = paginate(pagenum, pageSize,
				"select t1.*,t2.name,t2.website,t2.avatar,t2.email,t2.userip ",
				"from message t1,user t2 where t1.userid=t2.id order by t1.createtime desc");
		return page;
	}

	public Object findMsg4Page(Integer pageNum, Integer pageSize, Integer pid,
			Integer type, Boolean ispage, boolean isdesc) {
		String select = "select t1.id,t1.content,t1.createtime,t2.name,t2.avatar,t2.website ";
		String sqlExcept = "from message t1,user t2 where t1.userid=t2.id and t1.pid=? and t1.articleid=? order by t1.createtime "
				+ (isdesc ? "desc" : "asc");
		if (ispage) {
			return paginate(pageNum, pageSize, select, sqlExcept, new Object[] {
					pid, type });
		}
		return find(select + sqlExcept, new Object[] { pid, type });
	}

	public void deleteByMsgid(int msgid) {
		List<Message> msgs = find("select id from message where pid=?", msgid);
		for (Message msg : msgs) {
			deleteById(msg.getInt("id"));
		}
	}

}
